<?php

namespace App\Services\UserInviteInfo;

use App\Models\User;
use App\Models\Circle;
use Illuminate\Support\Str;
use Intervention\Image\Gd\Font;
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;

class MakeCircleInvitePoster
{
	/**
	 * @var User
	 */
	protected $user;
	
	/**
	 * @var Product
	 */
	protected $circle;
	
	protected $channel = 'wap';
	
	public function __construct(User $user, Circle $circle, $channel = 'wap')
	{
		$this->user = $user;
		$this->circle = $circle;
		$this->channel = $channel;
	}
	
	protected function getPosterName()
	{
		return "poster-user-{$this->user->id}-circle-{$this->circle->id}.png";
	}
	
	protected function getRemotePosterDir()
	{
		return 'images/mini-product-invite-posters';
	}
	
	protected function getRemotePosterSavePath()
	{
		return $this->getRemotePosterDir() . '/' . $this->getPosterName();
	}
	
	protected function getLocalPosterSavePath(string $name)
	{
		$localPath = public_path('temp/mini-product-invite-posters');
		if (! File::isDirectory($localPath)) {
			File::makeDirectory($localPath, 755, true, true);
		}
		return "{$localPath}/{$name}.png";
	}
	
	public function make()
	{
		$circle = $this->circle;
		
		/*if (Storage::exists($this->getRemotePosterSavePath())) {
			return Storage::url($this->getRemotePosterSavePath());
		}*/
		
		$posterDir = $this->getRemotePosterDir();
		$posterName = $this->getPosterName();

		$cover = ($circle->images)[0];
		$cover = Image::make(img_path($cover))->resize(708, 708);
		
		$footer = Image::make(oss('images/mini/product/poster-footer.png'))->resize(750, 183);
		
	
		$qrcode = Image::make($this->user->inviteQrcode())->resize(104, 104);

		
		Image::canvas(750, 913, '#FFFFFF')
			->insert($cover, 'top', 0, 22)
			->insert($footer, 'top', 0, 730)
			->insert($qrcode, 'bottom-right', 47, 50)
			->save($this->getLocalPosterSavePath($posterName));
		
		// move to oss.
		Storage::putFileAs($posterDir, $this->getLocalPosterSavePath($posterName), $posterName);
		
		// remove local poster.
		File::delete($this->getLocalPosterSavePath($posterName));
		
		return Storage::url("{$posterDir}/{$posterName}");
	}
}
